package com.myblog.controller;

import com.myblog.constant.CodeType;
import com.myblog.model.FeedBack;
import com.myblog.model.User;
import com.myblog.service.FeedBackService;
import com.myblog.service.UserService;
import com.myblog.utils.DataMap;
import com.myblog.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@Slf4j
@RestController
public class FeedBackController {
    @Autowired
    private FeedBackService feedBackService;

    @Autowired
    private UserService userService;
    /**
     * 后台管理获取所有反馈信息
     * @param rows
     * @param pageNum
     * @return
     */
    @GetMapping("/getAllFeedback")
    public String getAllFeedBackByPage(@RequestParam(value = "rows")Integer rows , @RequestParam(value = "pageNum")Integer pageNum){
        try{
            DataMap data = feedBackService.getAllFeedBackBypage(rows,pageNum);

            return JsonResult.build(data).toJSON();
        }catch (Exception e){
            log.error("FeedBackController getAllFeedBackByPage",e);
        }
        return JsonResult.fail().toJSON();
    }

    @PostMapping("/submitFeedback")
    public String submitFeedBack(FeedBack feedBack, HttpServletRequest request){
        try{
            Principal userPrincipal = request.getUserPrincipal();
            if(userPrincipal == null){
                return JsonResult.fail(CodeType.USER_NOT_LOGIN).toJSON();
            }
            User user = userService.searchUserByName(userPrincipal.getName());
            String username = user.getUsername();
            DataMap data = feedBackService.addFeedBack(feedBack,user.getId());

            return JsonResult.build(data).toJSON();
        }catch (Exception e){
            log.error("FeedBackController submitFeedBack",e);
        }
        return JsonResult.fail().toJSON();
    }
}
